package org.xtense.engine;

import java.text.MessageFormat;

import org.xtense.log.iLog;
import org.xtense.util.StringUtil;

public class SimpleQueryParser {
	private int documentID;
	private String xpath;
	private String pathExpression;
	private String advanceXpath;
	private String attributeName = null;
	
	public SimpleQueryParser(int documentID, String xpath) {
		this.xpath = xpath;
		this.documentID = documentID;
		init();
	}

	public boolean queryForAttribute() {
		return xpath.indexOf('[') < 0 && xpath.indexOf('@') > 0;
	}
	
	
	
	public String getAttributeName() {
		return attributeName;
	}

	private void init() {
		iLog.info("initialize the Query Parser");
		int pos = xpath.indexOf('[');
		if (pos < 0) {
			int atPos = xpath.indexOf('@');
			if (atPos > 0) {
				pathExpression = StringUtil.changeDelimiter(xpath.substring(0,
						atPos - 1));
				attributeName = xpath.substring(atPos + 1);
			} else {
				pathExpression = StringUtil.changeDelimiter(xpath);
			}
			
			advanceXpath = null;
		} else {
			pathExpression = StringUtil
					.changeDelimiter(xpath.substring(0, pos));
			while (xpath.charAt(pos) != '/') {
				pos--;
			}
			if (xpath.charAt(pos - 1) == '/') {
				advanceXpath = "/" + xpath.substring(pos);
			} else {
				advanceXpath = "/" + IConstants.tempRoot + xpath.substring(pos);
			}
		}
	}

	public String getPathQuery() {
		String sql = IConstants.Sql_Select_Two;
		String expressionOne;
		String expressionTwo = MessageFormat.format(IConstants.Sql_Int_Equal,
				new Object[] { IConstants.Document_ID, documentID });
		
		expressionOne = MessageFormat.format(IConstants.Sql_LIKE,
					new Object[] { IConstants.Path_Content,
							 pathExpression + "%" });
		

		return MessageFormat.format(sql, new Object[] { IConstants.Element_Pre,
				IConstants.Path_Table, expressionOne, expressionTwo });
	}

	public String getAdvancedPath() {
		return advanceXpath;
	}

}
